package com.bilgeadam.hibernate.model.dal;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.bilgeadam.hibernate.model.entity.Employee;
import com.bilgeadam.hibernate.model.util.HibernateUtil;

/**
 * 
 * @author Bora SAYINER
 * @since Nov 21, 2014 3:59:32 PM
 * @version 1.0.0
 */
@SuppressWarnings("unchecked")
public class EmployeeDal extends AbstractDal<Long, Employee> {

	@Override
	public List<Employee> getAll() {
		List<Employee> employees = null;
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		{
			try {
				employees = session.createQuery("FROM Employee").list();
				session.getTransaction().commit();
			} catch (Exception e) {
				e.printStackTrace();
				session.getTransaction().rollback();
			} finally {
				session.close();
			}
		}
		return employees;
	}

	@Override
	public Employee findById(Long id) {
		Employee employee = null;
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		{
			try {
				employee = (Employee) session.get(Employee.class, id);
				session.getTransaction().commit();
			} catch (Exception e) {
				e.printStackTrace();
				session.getTransaction().rollback();
			} finally {
				session.close();
			}
		}
		return employee;
	}

	@Override
	public boolean add(Employee entity) {
		boolean result = false;
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		{
			try {
				session.save(entity);
				session.getTransaction().commit();
				result = true;
			} catch (Exception e) {
				e.printStackTrace();
				session.getTransaction().rollback();
			} finally {
				session.close();
			}
		}
		return result;
	}

	@Override
	public boolean delete(Employee entity) {
		boolean result = false;
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		{
			try {
				session.delete(entity);
				session.getTransaction().commit();
				result = true;
			} catch (Exception e) {
				e.printStackTrace();
				session.getTransaction().rollback();
			} finally {
				session.close();
			}
		}
		return result;
	}

	@Override
	public boolean update(Employee entity) {
		boolean result = false;
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		{
			try {
				session.saveOrUpdate(entity);
				session.getTransaction().commit();
				result = true;
			} catch (Exception e) {
				e.printStackTrace();
				session.getTransaction().rollback();
			} finally {
				session.close();
			}
		}
		return result;
	}

}
